from flask_wtf import FlaskForm as _FlaskForm
from wtforms.validators import ValidationError


class Unique(object):
    def __init__(self, model, model_field, message=None):
        if message is None:
            message = 'The value of this field already exists'
        self.message = message
        self.model = model
        self.model_field = model_field

    def __call__(self, form, field):
        if field.object_data == field.data:
            return
        if self.model.query.filter(self.model_field == field.data).first():
            raise ValidationError(self.message)


class FlaskForm(_FlaskForm):
    def __init__(self, model=None, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.model = model

    @property
    def is_insert(self):
        return False if self.model is not None else True
